package com.werewolf;

import java.io.IOException;
import java.io.InputStream;
import java.io.StringReader;
import java.util.ArrayList;
import java.util.HashMap;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;

import android.app.ListActivity;
import android.content.res.Resources;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.Toast;

public class UltimateWerewolfActivity extends ListActivity 
{
	
	String XMLString;

	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState)
	{
		super.onCreate(savedInstanceState);
		setContentView(R.layout.listplaceholder);
		

		try {
			Resources res = getResources();
			InputStream inStream = res.openRawResource(R.raw.cards);
			byte [] readByte = new byte[inStream.available()];
			inStream.read(readByte);
			XMLString = new String(readByte);

		} catch (IOException e)
		{
			System.out.println("Could not read file" + e.getMessage());

		}
		
		ArrayList<HashMap<String,String>> mylist = new ArrayList<HashMap<String, String>>();


		Document doc = XMLData(XMLString);

		int numResult = numResults(doc);

		if(numResult <= 0)
		{
			Toast.makeText(UltimateWerewolfActivity.this, "No results Found" + numResult, Toast.LENGTH_LONG).show();
			finish();
		}

		NodeList nodes = doc.getElementsByTagName("Card");

		HashMap<String, String> map;
		for(int i = 0; i < nodes.getLength(); i++)
		{
			map = new HashMap<String, String>();
			Element e = (Element)nodes.item(i);
			map.put("RoleName", getValue(e, "RoleName"));
			map.put("RoleText", getValue(e, "RoleText"));
			map.put("RoleValue", getValue(e, "RoleValue"));
			map.put("RoleQuantity", getValue(e, "RoleQuantity"));
			mylist.add(map);
			map = null;
		}

		ListAdapter adapter = new SimpleAdapter(this, mylist, R.layout.main,
				new String [] { "RoleName","RoleText","RoleValue", "RoleQuantity" }, new int[] {R.id.RoleTitle,R.id.RoleText, R.id.RoleValue, R.id.RoleQuantity });

		setListAdapter(adapter);

		final ListView lv = getListView();
		lv.setTextFilterEnabled(true);
		lv.setOnItemClickListener(new OnItemClickListener() 
		{
			public void onItemClick(AdapterView<?> parent, View view, int position, long id) 
			{
				HashMap<String, String> o = (HashMap<String,String>) lv.getItemAtPosition(position) ;
				Toast.makeText(UltimateWerewolfActivity.this , "Role '" + o.get("RoleName") + "' was clicked!", Toast.LENGTH_LONG).show();

			}


		});

	}

	public Document XMLData(String XMLblob)
	{
		Document Doc = null;

		DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();

		try
		{
			DocumentBuilder db = dbf.newDocumentBuilder();
			InputSource inSource = new InputSource();
			inSource.setCharacterStream(new StringReader(XMLblob));
			Doc = db.parse(inSource);
		}
		catch(ParserConfigurationException e)
		{
			System.out.println( "XML Parse Error" +e.getMessage());
		} 
		catch (SAXException e)
		{
			// TODO Auto-generated catch block
			System.out.println( "" +e.getMessage());
		}
		catch (IOException e) 
		{
			// TODO Auto-generated catch block
			System.out.println( "" +e.getMessage());
		}

		return Doc;

	}



	static int numResults(Document doc)
	{		
		int res = -1;
		Node Results = doc.getDocumentElement();
		try
		{
			res = Integer.valueOf(Results.getAttributes().getNamedItem("count").getNodeValue());
		}
		catch(Exception e)
		{
			res = -1;
		}
		
		return res;
	}

	final static String getElementValue(Node element)
	{
		Node child;
		String ret = "";
		if(element != null)
		{
			if(element.hasChildNodes() )
			{
				child = element.getFirstChild();
				while(  child != null )
				{
					if(child.getNodeType() == Node.TEXT_NODE)
					{
						ret = child.getNodeValue();
						child = null;
					}
					else
					{
						child.getNextSibling();
					}
				}

			}
		}
		return ret;
	}

	String getValue(Element item, String str)
	{
		NodeList n = item.getElementsByTagName(str);
		return getElementValue(n.item(0));
	}

	
	



}